﻿using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Resources;

using FirstFloor.Documents.IO;
using Ionic.Zip;

namespace DotNetZip
{
    /// <summary>
    /// Encapsulates a zip package part request.
    /// </summary>
    public class DotNetZipPackagePartRequest
        : SyncPackagePartRequest
    {
        private ZipFile zipFile;
        private Uri partUri;
        /// <summary>
        /// Initializes a new instance of the <see cref="DotNetZipPackagePartRequest"/> class.
        /// </summary>
        /// <param name="zipFile">The zip file.</param>
        /// <param name="partUri">The part URI.</param>
        internal DotNetZipPackagePartRequest(ZipFile zipFile, Uri partUri)
        {
            this.zipFile = zipFile;
            this.partUri = partUri;
        }

        /// <summary>
        /// Loads the requested part synchronously.
        /// </summary>
        /// <returns>The part content stream.</returns>
        protected override Stream LoadPart()
        {
            var entry = this.zipFile[this.partUri.OriginalString];
            if (entry != null) {
                var stream = new MemoryStream();
                entry.Extract(stream);

                // reset position
                stream.Seek(0, SeekOrigin.Begin);

                return stream;
            }
            return null;
        }
    }
}
